package edu.whu.puppygo.sacnner;

import edu.whu.puppygo.dao.FragmentDao;
import edu.whu.puppygo.entity.FragmentStatueEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author guanruwang
 * @date 2023/12/8$
 */
@Component
@Slf4j
public class FragmentTimeoutScanner {

    @Resource
    private FragmentDao fragmentDao;

    /**
     * &#064;description:  gpt超时时间180秒，
     */
    @Scheduled(fixedRate = 180 * 1000)
    public void scan() {
        List<FragmentStatueEnum> list = Collections.singletonList(FragmentStatueEnum.EMBEDDING_FINISHED);
        fragmentDao.findByStatueIn(list).forEach(fragment -> {
            if (fragment.getUpdateTime().plusSeconds(180).isBefore(LocalDateTime.now())) {
                fragment.setStatue(FragmentStatueEnum.GPT_TIMEOUT);
                fragmentDao.save(fragment);
                log.info("问答超时，Id：{}", fragment.getId());
            }
        });
    }

    /**
     * &#064;description:  embedding，vqa超时时间180秒，
     */
    @Scheduled(fixedRate = 180 * 1000)
    public void scan2() {
        List<FragmentStatueEnum> list = Arrays.asList(FragmentStatueEnum.DB_INSERT_FINISHED, FragmentStatueEnum.VQA_FINISHED);
        fragmentDao.findByStatueIn(list).forEach(fragment -> {
            if (fragment.getUpdateTime().plusSeconds(90).isBefore(LocalDateTime.now())) {
                if (fragment.getStatue() == FragmentStatueEnum.VQA_FINISHED) {
                    fragment.setStatue(FragmentStatueEnum.EMBEDDING_TIMEOUT);
                    fragmentDao.save(fragment);
                    log.info("问答超时，Id：{}", fragment.getId());
                    return;
                }
                if (fragment.getStatue() == FragmentStatueEnum.DB_INSERT_FINISHED) {
                    if (fragment.getImgUrl() != null) {
                        fragment.setStatue(FragmentStatueEnum.VQA_TIMEOUT);
                        fragmentDao.save(fragment);
                        log.info("问答超时，Id：{}", fragment.getId());
                        return;
                    }
                    fragment.setStatue(FragmentStatueEnum.EMBEDDING_TIMEOUT);
                    fragmentDao.save(fragment);
                    log.info("问答超时，Id：{}", fragment.getId());
                }

            }
        });
    }
}
